package com.example.buy.service.impl;

import com.example.buy.VO.UserVO;
import com.example.buy.model.User;
import com.example.buy.redis.UserRedis;
import com.example.buy.repository.UserRepository;
import com.example.buy.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    public UserRepository userRepository;
    @Autowired
    public UserRedis userRedis;

    @Override
    public User regist(User user) {
        return userRepository.saveAndFlush(user);
    }

    @Override
    public UserVO getUser(String username) {//查询到该账户就将该账户存储在redis中
        UserVO userVO = new UserVO();
        User user = userRedis.get(username);
        if(user == null) {
            user = userRepository.findByUsername(username);
            if(user != null){
                userRedis.put(user.getUsername(),user,-1);
            }else{
                return null;
            }
        }
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }
    @Override
    public Object getUserFromRedisByToken(String token) {//分布式系统获取session的方式
        return userRedis.get(token);
    }

    @Override
    public void saveUserToRedisByToken(UserVO dbUser, String token) {
        User user = new User();
        BeanUtils.copyProperties(dbUser,user);
        userRedis.put(token,user,3600);
    }
}
